import json

import redis
from celery_tas.Celery.celery import sms_code
from utils.captcha import Captcha
from io import BytesIO
from flask import Blueprint, jsonify, g, request, make_response
from werkzeug.security import generate_password_hash, check_password_hash
from flask_restful import Api,Resource, reqparse,marshal

from utils.es.es import ES
from utils.jwt_util import _generate_token
from models import db
from models.Courses import *
from models.perssiones import Roles
from models.user import *
from utils.model_fields.user import *
from utils.login_utils import login_required

course_bp = Blueprint('course', __name__, url_prefix='/course')
api = Api(course_bp)


class Course_Tag(Resource):
    def get(self):
        coursestag = CourseTag.query.filter_by().all()
        return {"data": marshal(coursestag, coursestag_fields)}


class Course_(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        list1 = ["page", "size", "tag_id", "free", "online", "sort"]
        for i in list1:
            parser.add_argument(i)
        args = parser.parse_args()
        page = args.get("page")
        size = args.get("size")
        tag_id = args.get("tag_id")
        free = args.get("free")
        online = args.get("online")
        sort = args.get("sort")
        print("标签》》》", tag_id, "类别》》》",  free, "上没上线》》》",  online, "以什么排序",  sort)
        if free == '免费':
            free = 1
        if free == '限免':
            free = 2
        if free == '会员':
            free = 3
        data_ = []
        # 判断是否是类别全部
        if free != '':
            # 不是全部类别
            courseandcategory = CourseandCategory.query.filter_by(category_id=free).all()  # 根据类别查询数据
            data_a = []
            # 判断是否是全部标签
            if tag_id != '':
                # 不是全部标签
                courseandag = CourseandTag.query.filter_by(tag_id=tag_id).all()  # 根据标签查询数据
                data_b = []
                # 判断是否是全部状态
                if online != '':
                    # 不是全部状态
                    for i in courseandcategory:
                        courseandcategory_ = Course.query.filter_by(id=i.course_id, course_status=online).first()
                        data_a.append(courseandcategory_)
                    for i in courseandag:
                        courseandag_ = Course.query.filter_by(id=i.course_id, course_status=online).first()
                        data_b.append(courseandag_)
                    # 判断两个表是否只查到了数据
                    if (data_b is not None) and (data_a is not None):
                        # 判断类别表是否只只查到了一个数据
                        if len(data_a) == 1:
                            # 判断标签表是否只只查到了一个数据
                            if len(data_b) == 1:
                                # 判断数据是否一致 一致则添加
                                print(data_a[0].id, data_b[0].id)
                                if data_a == data_b and data_a != None:
                                    data_ = marshal(data_a, course_fields)
                            # 如果标签表有一个以上的数据
                            else:
                                # 开始循环标签表
                                for j in data_b:
                                    # 进行判断如果数据一致则添加数据并结束循环
                                    if j == data_a and j != None:
                                        data_.append(marshal(j, course_fields))
                                        break
                        #  如果类别表有一个以上的数据   进行判断标签表是否只只查到了一个数据
                        elif len(data_b) == 1:
                            # 判断查询出的两个表里的数据是否一致   一致则添加
                            if data_a == data_b and data_a != None:
                                data_.append(marshal(data_a, course_fields))
                        #   如果标签表也有一个及以上的数据  则开始双重循环
                        else:
                            for i in data_a:
                                for j in data_b:
                                    # 判断数据是否一致 一致则添加并退出当前子循环，让父循环进行下一次循环
                                    if i == j and i != None:
                                        data_.append(marshal(i, course_fields))
                                        break
                #   是全部状态
                else:
                    for i in courseandcategory:
                        courseandcategory_ = Course.query.filter_by(id=i.course_id).first()
                        data_a.append(courseandcategory_)
                    for i in courseandag:
                        courseandag_ = Course.query.filter_by(id=i.course_id).first()
                        data_b.append(courseandag_)
                    # 判断两个表是否只查到了数据
                    if (data_b is not None) and (data_a is not None):
                        # 判断类别表是否只只查到了一个数据
                        if len(data_a) == 1:
                            # 判断标签表是否只只查到了一个数据
                            if len(data_b) == 1:
                                # 判断数据是否一致 一致则添加
                                print(data_a[0].id, data_b[0].id)
                                if data_a == data_b and data_ != None:
                                    data_ = marshal(data_a, course_fields)
                            # 如果标签表有一个以上的数据
                            else:
                                # 开始循环标签表
                                for j in data_b:
                                    # 进行判断如果数据一致则添加数据并结束循环
                                    if j == data_a and j != None:
                                        data_.append(marshal(j, course_fields))
                                        break
                        #  如果类别表有一个以上的数据   进行判断标签表是否只只查到了一个数据
                        elif len(data_b) == 1:
                            # 判断查询出的两个表里的数据是否一致   一致则添加
                            if data_a == data_b:
                                data_.append(marshal(data_a, course_fields))
                        #   如果标签表也有一个及以上的数据  则开始双重循环
                        else:
                            for i in data_a:
                                for j in data_b:
                                    # 判断数据是否一致 一致则添加并退出当前子循环，让父循环进行下一次循环
                                    if i == j and i != None:
                                        data_.append(marshal(i, course_fields))
                                        break
            #  是全部标签   判断是否是全部状态
            elif online != '':
                courseandcategory = CourseandCategory.query.filter_by(category_id=free).all()   # 根据类别查询数据
                # 循环查到的类别表里的数据
                for i in courseandcategory:
                    courseandcategory_ = Course.query.filter_by(id=i.course_id, course_status=online).first()    #  根据状态查询数据
                    # 判断是否查到了数据
                    if courseandcategory_:
                        data_.append(marshal(courseandcategory_, course_fields))
            #   是全部状态
            else:
                courseandcategory = CourseandCategory.query.filter_by(category_id=free).all()   # 根据类别查询中间表数据
                # 循环查到的类别表里的数据
                for i in courseandcategory:
                    courseandcategory_ = Course.query.filter_by(id=i.course_id).first()   # 根据中间表数据查询课程表的数据
                    # 判断是否查到了数据
                    if courseandcategory_:
                        data_.append(marshal(courseandcategory_, course_fields))
        #   类别是全部类别   判断是否是全部标签
        elif tag_id != '':
            # 不是全部标签
            courseandag = CourseandTag.query.filter_by(tag_id=tag_id).all()   # 根据标签查询课程表和标签表的中间表
            # 判断是否 是全部状态
            if online != '':
                # 不是全部状态 循坏中间表数据
                for i in courseandag:
                    # 根据中间表数据查询课程表信息
                    course = Course.query.filter_by(id=i.course_id, course_status=online).first()
                    # 判断查询的数据是否为空
                    if course is None:
                        continue
                    data_.append(marshal(course, course_fields))
            #   是全部状态
            else:
                # 训环中间表数据
                for i in courseandag:
                    # 根据中间表数据查询课程表数据
                    course = Course.query.filter_by(id=i.course_id).first()
                    data_.append(marshal(course, course_fields))
        #   判断类别是否是全部类别和是否全部标签
        if ([tag_id, free] == ['', '']) and online != '':
            course_ = Course.query.filter_by(course_status=online).all()
            data_ = marshal(course_, course_fields)
        #   判断类别是否是全部类别、是否是全部标签和是否是全部状态
        if [tag_id, free, online] == ['', '', '']:
            course_ = Course.query.all()
            data_ = marshal(course_, course_fields)
        a = 0
        for i in data_:
            courseandcategory = CourseandCategory.query.filter_by(course_id=i.get('id')).first()
            category = Category.query.filter_by(id=courseandcategory.category_id).first()
            if category.category_name == 0:
                i['category'] = '免费'
            if category.category_name == 1:
                i['category'] = '限免'
            if category.category_name == 2:
                i['category'] = '会员'
                data_[a] = i
            a += 1
        data_ = self.fun(data_, sort)
        return {"data": data_}

    @staticmethod
    def fun(data, a):
        if a == 1:
            pass
        elif a == 2:
            pass
        return data


class CourseInfo(Resource):

    @login_required
    def get(self):
        parser = reqparse.RequestParser()
        list1 = ["cid", "token"]
        for i in list1:
            parser.add_argument(i)
        args = parser.parse_args()
        cid = args.get('cid')
        try:
            vip = VipModel.query.filter_by(user=g.user_id).first()
        except Exception as e:
            return jsonify(message="用户不存在", code=401)
        # 会员用户可以观看免费的,普通用户只能观看免费的视频
        # role_id = vip.level # 当前用户的等级
        # 获取当前用户等级的权限
        role = Roles.query.filter_by(id=vip.level).first()
        # 是权限的列表
        permissons = role.permission
        # 获取当前请求的url
        if str(request.url) not in permissons:
            return jsonify(message="没有权限,请升级会员", code=403)

        # 生成课程信息
        course_ = Course.query.filter_by(id=cid).first()
        course_ser = marshal(course_, course_fields)
        course_ser_dict = json.loads(json.dumps(course_ser))

        # 生成课程的章程信息
        chapter_ = Chapters.query.filter_by(course=course_.id).all()
        section_ser = []
        for i in chapter_:
            section_ser.append(marshal(i, chapter_fields))
        section_ser_dict = json.loads(json.dumps(section_ser))
        a = 0
        for i in section_ser_dict:
            sections_ser = []
            sections_ = Sections.query.filter_by(chapters=i.get('id')).all()
            for j in sections_:
                sections_ser.append(marshal(j, sections_fields))
            sections_ser = json.loads(json.dumps(sections_ser))
            i['section_list'] = sections_ser
            section_ser_dict[a] = i
            a += 1
        data_ = {
            "section_ser": section_ser_dict,
            "course_ser": course_ser_dict,
        }
        return jsonify(code=200, data=data_)


class Sectionvideo_Get(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        list1 = ["sid"]
        for i in list1:
            parser.add_argument(i)
        args = parser.parse_args()
        sid = args.get('sid')
        sections_ = Sections.query.filter_by(id=sid).first()
        sections_data = marshal(sections_, sections_fields)
        return jsonify(data=sections_data)


class Courserecord(Resource):
    @login_required
    def get(self):
        parser = reqparse.RequestParser()
        list1 = ["sid", "cid"]
        for i in list1:
            parser.add_argument(i)
        args = parser.parse_args()
        sid = args.get('sid')
        cid = args.get('cid')
        sections_ = Sections.query.filter_by(id=cid).first()
        sections_data = marshal(sections_, sections_fields)
        sect_ = SectionsandUser.query.filter_by(sections_id=sid).first()
        if sect_ is not None:
            SectionsandUser.query.filter_by(sections_id=sid).update({'guankan': 1})
        else:
            sa = SectionsandUser(user_id=g.user_id, sections_id=sid, guankan=1)
            db.session.add(sa)
            db.session.commit()
        return jsonify(data=sections_data)


class Comment_get(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        list1 = ["course_id"]
        for i in list1:
            parser.add_argument(i)
        args = parser.parse_args()
        course_id = args.get('course_id')
        comment_ = Comments.query.filter_by(course=course_id).all()
        data = []
        for i in comment_:
            user = UserModels.query.filter_by(uid=i.user).first()
            if i.parent_id is not None:
                comment = Comments.query.filter_by(id=i.parent_id).first()
                user_ = UserModels.query.filter_by(uid=comment.user).first()
                data_ = {
                    'id': i.id,
                    'user': i.user,
                    'comment_time': str(i.comment_time),
                    'comment_content': i.comment_content,
                    'is_favorite': i.zan_num,
                    'parent_id': i.parent_id,
                    'course': i.course,
                    'reply_count': i.reply_count,
                    'is_top': i.is_top,
                    'username': user.account,
                    'username_': user.account,
                    "like_count": user_.account,
                    "profile_photo": user_.profile_photo,
                    "childlist": [],
                }
                data[i.parent_id-1].get('childlist').append(data_)
            else:
                data_ = {
                    'id': i.id,
                    'user': i.user,
                    'comment_time': str(i.comment_time),
                    'comment_content': i.comment_content,
                    'is_favorite': i.zan_num,
                    'parent_id': i.parent_id,
                    'course': i.course,
                    'reply_count': i.reply_count,
                    'is_top': i.is_top,
                    'username': user.account,
                    "profile_photo": user.profile_photo,
                    "childlist": [],
                }
                data.append(data_)
        return jsonify(data=data)


class CommentAddComment(Resource):
    @login_required
    def post(self):
        parser = reqparse.RequestParser()
        list1 = ["content", "token", "ques_id", "reply"]
        for i in list1:
            parser.add_argument(i)
        args = parser.parse_args()
        content = args.get('content')
        token = args.get('token')
        ques_id = args.get('ques_id')
        reply = args.get('reply')
        id = g.user_id
        if not reply:
            comments_ = Comments(user=id, comment_content=content, course=ques_id)
            db.session.add(comments_)
            db.session.commit()
            return jsonify(message="发布成功")
        else:
            comments_ = Comments(user=id, comment_content=content, course=ques_id, parent_id=reply)
            db.session.add(comments_)
            db.session.commit()
            data = {
                "message": "回复成功"
            }
            return jsonify(data=data)


# 评论的收藏
class Favorite_Comment(Resource):
    @login_required
    def post(self):
        parser = reqparse.RequestParser()
        list1 = ["com_id", "receive_id", "token"]
        for i in list1:
            parser.add_argument(i)
        args = parser.parse_args()
        com_id = args.get('com_id')
        token = args.get('token')
        receive_id = args.get('receive_id')
        id = g.user_id
        comment_ = Comments.query.filter_by(id=com_id).first()
        if comment_.zan_num == 0:
            Comments.query.filter_by(id=com_id).update({'zan_num': 1})
            db.session.commit()
            return jsonify(msg="点赞成功", code=200)
        else:
            Comments.query.filter_by(id=com_id).update({'zan_num': 0})
            db.session.commit()
            return jsonify(msg="取消点赞成功", code=200)


# 收藏与取消收藏
class Hoarding_Course(Resource):
    @login_required
    def post(self):
        parser = reqparse.RequestParser()
        list1 = ["id"]
        for i in list1:
            parser.add_argument(i)
        args = parser.parse_args()
        id = args.get('id')
        course_ = Course.query.filter_by(id=id).first()
        if course_.is_attention == 0:
            Course.query.filter_by(id=id).update({'is_attention': 1, "attention": course_.attention + 1})
            db.session.commit()
            return jsonify(msg="收藏成功", code=200, data={'attention': course_.attention + 1})
        else:
            Course.query.filter_by(id=id).update({'is_attention': 0, "attention": course_.attention - 1})
            db.session.commit()
            return {"msg": "取消收藏成功", "code": 200, "attention": course_.attention-1}


# 搜索
class Search(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('q')
        args = parser.parse_args()
        q = args.get('q')
        es = ES('tb_course')
        result = es.search(q)
        print("result...", result)


api.add_resource(Course_Tag, '/get_tag')
api.add_resource(Course_, '/get_course')
api.add_resource(CourseInfo, '/courseinfo')
api.add_resource(Sectionvideo_Get, '/sectionvideo')
api.add_resource(Courserecord, '/courserecord/')
api.add_resource(Comment_get, '/comment/get_comment')
api.add_resource(CommentAddComment, '/comment/add_comment')
api.add_resource(Favorite_Comment, '/favorite_comment/')
api.add_resource(Hoarding_Course, '/hoarding_course')
api.add_resource(Search, '/search')






